import { useState, useEffect, useRef } from 'react'
function MiaoSha(props) {
    // props.count 来代表秒杀的倒计时时长
    const [time, setTime] = useState(props.count || 3) // 初始化倒计时的时长
    const hRef = useRef(null)
    useEffect(() => {
        // 开启定时器进行秒杀倒计时
        const timer = setInterval(() => {
            if (time > 1) {
                setTime(time - 1);
                hRef.current.classList.remove('animate__animated', 'animate__' + props.animate)
                hRef.current.offsetWidth; // 触发重绘
                hRef.current.classList.add('animate__animated', 'animate__' + props.animate)
            } else {
                setTime('秒杀开始！')
                clearInterval(timer)
            }
        }, 1000)

        return () => {
            timer && clearInterval(timer)
        }
    }, [time])

    return <h1 ref={hRef} style={{ color: 'red' }} className={'animate__animated animate__' + props.animate}>
        {time}
    </h1>
}

export default MiaoSha